package com.jyhg.core.mobile.utils.timer
{
	import flash.utils.getTimer;
	
	import starling.animation.IAnimatable;
	import starling.core.Starling;

	public class TimerManager implements IAnimatable
	{
		private var _funVector:Vector.<Function> = new Vector.<Function>;
		public function TimerManager()
		{
		}
		
		private var _currentTimer:int=0;
		private var _oldTimer:int=0;
		public function advanceTime(time:Number):void
		{
			_currentTimer = getTimer();
			if(_currentTimer-_oldTimer>=1000)
			{
				timerHandle();
				_oldTimer = _currentTimer;
			}
		}
		
		public function dispose():void
		{
			_funVector.length = 0;
		}
		
		public function addTimerEvent(fun:Function):void
		{
			if(_funVector.indexOf(fun)!=-1)return;
			Starling.juggler.add(this)
			_funVector.push(fun);
		}
		
		private function timerHandle():void
		{
			var len:int = _funVector.length;
			
			if(_funVector.length==0)
			{
				Starling.juggler.remove(this);
				return;
			}
			
			for(var i:int=0;i<_funVector.length;i++)
			{
				_funVector[i]();
			}			
		}
		
		
		/**
		 *  移除计时的函数
		 * @param fun
		 * 
		 */		
		public function removeTimerEvent(fun:Function):void
		{
			var index:int = _funVector.indexOf(fun)
			if(index!=-1)
			{
				_funVector.splice(index,1);
			}
		}
		
		private static var _instance:TimerManager;
		public static function getInstance():TimerManager
		{
			_instance ||= new TimerManager();
			return _instance;
		}
	}
}